package gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author viento
 * @Date 2018/10/31 9:54
 * @Description TokenFilter 判断Authorization与url是否具有相应的权限
 * @Link 3576993219
 */
//@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        if (!ctx.sendZuulResponse()) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("2");
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String uri = request.getRequestURI();
        List<String> uriRoles = getUriRoles(uri);
        List<String> curRoles = (List<String>) requestContext.get("curRoles");
        if (!CollectionUtils.isEmpty(curRoles)){
            uriRoles.retainAll(curRoles);

            if (uriRoles.size()>=1){
                System.out.println("当前 角色访问 URL 合法");
                System.out.println("Authorization: "+ requestContext.get("Authorization"));
                System.out.println("uri: " + uri);
                System.out.println("roles: " + uriRoles.toString());
            }else {
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(200);
                Map<String,String> responseMap=new HashMap<>();
                responseMap.put("code", "401");
                responseMap.put("msg", "You have no access to the current URL.");
                requestContext.setResponseBody(JSON.toJSONString(responseMap));
            }
        }
        return null;
    }


    public static List<String> getUriRoles(String uri) {
        List<String> uriRoles = new ArrayList<>();
        uriRoles.add("write");
        uriRoles.add("admin");
        uriRoles.add("1111111");
        return uriRoles;
    }

}
